package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundInOutRQueryCondition;
import cn.fl.capital.condition.CapFundIntoLogQueryCondition;
import cn.fl.capital.service.ICapFundInOutRService;
import cn.fl.capital.service.ICapFundIntoLogService;
import cn.fl.capital.service.ICapFundOutApplyService;
import cn.fl.capital.vo.CapFundInOutRVO;
import cn.fl.capital.vo.CapFundIntoLogVO;
import cn.fl.capital.vo.CapFundOutApplyVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 资金池管理控制层
 * @Author: liurong
 * @CreateDate: 2018/10/31 11:33
 * @Version: 1.0
 */
@Controller
@RequestMapping("/capital/capFundPool")
public class CapFundPoolController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CapFundPoolController.class);

    @Autowired
    private ICapFundIntoLogService capFundIntoLogService;

    @Autowired
    private ICapFundOutApplyService capFundOutApplyService;

    @Autowired
    private ICapFundInOutRService capFundInOutRService;

    /**
     * 到资金池管理页面
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @throws
     * @author liurong
     * @date 2018/10/31 13:50
     */
    @RequestMapping(value = "/toManagePage.do", method = {RequestMethod.GET})
    public ModelAndView toManagePage() {
        BaseLogUtils.info(logger, "toManagePage", "加载到资金池管理页面页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("capital/capFundPool/capFundPool");
        return view;
    }

    /**
     * Tab页面切换控制方法
     *
     * @param request
     * @return org.springframework.web.servlet.ModelAndView
     * @throws
     * @author liurong
     * @date 2018/10/31 17:59
     */
    @RequestMapping(value = "/enterTabPage.do", method = {RequestMethod.GET})
    public ModelAndView enterTabPage(HttpServletRequest request) {
        String type = request.getParameter("type");
        ModelAndView view = null;
        if ("1".equals(type)) {
            BaseLogUtils.info(logger, "enterTabPage", "加载到待使用资金列表页面.", CurrentThreadContext.getCurrentUserName());
            view = new ModelAndView("capital/capFundPool/capFundToBeUsedList");
        } else if ("2".equals(type)) {
            BaseLogUtils.info(logger, "enterTabPage", "加载到历史转出/入记录列表页面.", CurrentThreadContext.getCurrentUserName());
            view = new ModelAndView("capital/capFundPool/capFundTransRecordList");
        } else {

        }
        return view;
    }

    /**
     * 待使用资金资金池列表数据
     *
     * @param request
     * @param condition
     * @return
     * @throws
     * @author liurong
     * @date 2018/11/2 8:55
     */
    @RequestMapping(value = "/fundsToBeUsedList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object fundsToBeUsedList(HttpServletRequest request, CapFundIntoLogQueryCondition condition) {
        int totalCount = 0;
        List<CapFundIntoLogVO> list = null;
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");
            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            condition = setNullValue(condition);

            // 处理金额，转换为分
            if (StringUtils.isNotEmpty(condition.getAvailableAmountMin())) {
                condition.setAvailableAmountMin(DecimalUtils.convertYuanToFen(condition.getAvailableAmountMin().doubleValue()));
            }
            if (StringUtils.isNotEmpty(condition.getAvailableAmountMax())) {
                condition.setAvailableAmountMax(DecimalUtils.convertYuanToFen(condition.getAvailableAmountMax().doubleValue()));
            }

            page.setCondition(condition);

            Pager pager = capFundIntoLogService.selectFundToBeUsedListPage(page);


            if (pager != null) {
                list = (List<CapFundIntoLogVO>) pager.getResultList();
                totalCount = pager.getTotalCount();
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "fundsToBeUsedList", "初始化待使用资金池列表页面数据异常", e);
        }

        ListPageVO<CapFundIntoLogVO> listPage = new ListPageVO<CapFundIntoLogVO>(list, totalCount);
        return listPage;
    }

    /**
     * 初始化历史转入/出记录列表数据
     * @param request
     * @param condition
     * @return
     */
    @RequestMapping(value = "/fundsHistoryList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object fundsHistoryList(HttpServletRequest request, CapFundInOutRQueryCondition condition) {
        int totalCount = 0;
        List<CapFundInOutRVO> list = null;
        try{
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");
            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            condition = setNullValue(condition);

            // 处理金额，转换为分
            if (StringUtils.isNotEmpty(condition.getAvailableAmountMin())) {
                condition.setAvailableAmountMin(DecimalUtils.convertYuanToFen(condition.getAvailableAmountMin().doubleValue()));
            }
            if (StringUtils.isNotEmpty(condition.getAvailableAmountMax())) {
                condition.setAvailableAmountMax(DecimalUtils.convertYuanToFen(condition.getAvailableAmountMax().doubleValue()));
            }
            page.setCondition(condition);

            Pager pager = capFundInOutRService.selectTransHistoryList(page);

            if (pager != null) {
                list = (List<CapFundInOutRVO>) pager.getResultList();
                totalCount = pager.getTotalCount();
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "fundsHistoryList", "初始化历史转入/出列表页面数据异常", e);
        }
        ListPageVO<CapFundInOutRVO> listPage = new ListPageVO<>(list, totalCount);
        return listPage;
    }

    /**
     * 进入转来款申请页面
     *
     * @param request
     * @return
     * @throws
     * @author liurong
     * @date 2018/11/2 10:12
     */
    @RequestMapping(value = "/toTransIncomePage.do", method = {RequestMethod.GET})
    public ModelAndView toTransIncomePage(HttpServletRequest request) {
        // 动作类型：1-新增  2-修改  3-查看
        String action = request.getParameter("action");
        // 申请记录ID
        String oaId = request.getParameter("outApplyId");
        // 资金池转入记录表ID
        String intoIds = null;

        Long outApplyId;
        ModelAndView view = new ModelAndView("capital/capFundPool/capFundApplyTransIncome");
        if (StringUtils.isNotBlank(oaId)) {
            // 请求url中带有outApplyId
            outApplyId = Long.parseLong(oaId);

            // 查询申请记录信息
            CapFundOutApplyVO capFundOutApplyVO = capFundOutApplyService.selectById(outApplyId);
            if (capFundOutApplyVO != null) {
                view.addObject("outRem", capFundOutApplyVO.getOutRem());

                // 根据申请记录ID，查询转入记录ID
                CapFundInOutRQueryCondition condition = new CapFundInOutRQueryCondition();
                condition.setOutApplyId(outApplyId);
                List<CapFundInOutRVO> capFundInOutRVOS = capFundInOutRService.searchList(condition);
                StringBuilder stb = new StringBuilder();
                if (capFundInOutRVOS.size() > 0) {
                    for (int i = 0; i < capFundInOutRVOS.size(); i++) {
                        CapFundInOutRVO vo = capFundInOutRVOS.get(i);
                        stb.append(vo.getFundIntoId()).append(",");
                    }
                    intoIds = stb.substring(0, stb.length() - 1);
                }
            }
        } else {
            // 请求url中不带有outApplyId，
            intoIds = request.getParameter("intoIds");
            // 先获取申请ID，让上传的资料能先关联上，防止回显不了资料信息，新增申请的时候，以此作为PK,insert
            outApplyId = capFundOutApplyService.queryTheNextPk();

        }
        view.addObject("intoIds", intoIds);
        view.addObject("currentUserName", CurrentThreadContext.getCurrentUserName());
        view.addObject("currentTime", DateUtils.getCurrentDateStr(DateUtils.YYYY_MM_DDHHMMSS));
        view.addObject("outApplyId", outApplyId);
        view.addObject("action", action);

        return view;
    }

    /**
     * 转来款申请页面，加载资金列表数据
     *
     * @param request
     * @return
     * @throws
     * @author liurong
     * @date 2018/11/2 10:13
     */
    @RequestMapping(value = "/fundsToApplyTransIncomeList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object fundsToBeUsedList(HttpServletRequest request) {
        List<CapFundIntoLogVO> voList = null;
        try {
            String intoIds = request.getParameter("intoIds");
            if (StringUtils.isNotBlank(intoIds)) {
                String[] idArray = intoIds.split(",");
                List<Long> idList = new ArrayList<>(idArray.length);
                for (String id : idArray) {
                    if (StringUtils.isNotEmpty(id)) {
                        idList.add(Long.parseLong(id));
                    }
                }

                voList = capFundIntoLogService.selectFundsToApplyTransIncomeList(idList);
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "fundsToBeUsedList", "初始化待使用资金池列表页面数据异常", e);
        }
        ListPageVO<CapFundIntoLogVO> listPage = new ListPageVO<CapFundIntoLogVO>(voList, null);
        return listPage;
    }

    /**
     * 提交转来款申请
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/commitApply.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object commitApply(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String outRem = request.getParameter("outRem");
            String intoIds = request.getParameter("intoIds");
            String outApplyId = request.getParameter("outApplyId");
            if (StringUtils.isNotBlank(intoIds)) {
                String[] idArray = intoIds.split(",");
                List<Long> idList = new ArrayList<>(idArray.length);
                for (String id : idArray) {
                    if (StringUtils.isNotEmpty(id)) {
                        idList.add(Long.parseLong(id));
                    }
                }
                CapFundOutApplyVO entity = new CapFundOutApplyVO();
                entity.setId(Long.parseLong(outApplyId));
                entity.setOutRem(outRem);
                entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
                entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());

                capFundOutApplyService.addOutApplyAndBusi(entity, idList);
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "commitApply", "新增转来款申请操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 修改申请信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyApply.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyApply(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String outRem = request.getParameter("outRem");
            String intoIds = request.getParameter("intoIds");
            String outApplyId = request.getParameter("outApplyId");

            if (StringUtils.isNotBlank(intoIds)) {
                String[] idArray = intoIds.split(",");
                List<Long> idList = new ArrayList<>(idArray.length);
                for (String id : idArray) {
                    if (StringUtils.isNotEmpty(id)) {
                        idList.add(Long.parseLong(id));
                    }
                }
                CapFundOutApplyVO entity = new CapFundOutApplyVO();
                entity.setId(Long.parseLong(outApplyId));
                entity.setOutRem(outRem);
                entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
                entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());

                capFundOutApplyService.modifyOutApplyAndBusi(entity, idList);
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modifyApply", "修改转来款申请操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 将对象中为空字符串的属性置为null
     *
     * @param source
     * @return
     * @throws
     * @author liurong
     * @date 2018/11/2 8:56
     */
    private <T> T setNullValue(T source) throws IllegalArgumentException, IllegalAccessException, SecurityException {
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getGenericType().toString().equals("class java.lang.String")) {
                field.setAccessible(true);
                Object obj = field.get(source);
                if (obj != null && obj.equals("")) {
                    field.set(source, null);
                }
            }
        }
        return source;
    }


}
